////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity.groups.index;

import java.util.List;
import java.util.Vector;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.CustomizeDialog;
import cc.telecomdigital.tdstock.DBHelper;
import cc.telecomdigital.tdstock.DefaultClickHandler;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.LightStreamerHandlerInterface;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.StringUtils;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Services.LS_SubscriptionItem;
import cc.telecomdigital.tdstock.Services.LS_UserClient.ILS_UserClient_Response;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.BaseActivity;
import cc.telecomdigital.tdstock.activity.groups.IndexGroup;
import cc.telecomdigital.tdstock.activity.groups.monitor.util.MonitorUtil;
import cc.telecomdigital.tdstock.activity.groups.monitor.util.SaveBookMarkAsyncTask;
import cc.telecomdigital.tdstock.adapter.IndexCopHolder;
import cc.telecomdigital.tdstock.model.IndexFuturesInfo;

import com.lightstreamer.ls_client.UpdateInfo;

/**
 * 
 * @author haibo
 * 
 *         for top bar button named "options"
 * 
 */
public class IndexCOPListActivity extends BaseActivity implements
	ILS_UserClient_Response
{

	protected static final String			TAG				= IndexCOPListActivity.class
															.getSimpleName();
	private static final String[]			INDEX_FUTURES_ITEMS	= { "HSI:1",
			"HSI:2", "HHI:1", "HHI:2"					};

	private ListView					_listView;
	private IndexCopItemAdapter			_adapter;
	private List<IndexCopHolder>			_list;
	private Button						_toolBtnReturn;

	private TextView					_top_bar_title;

	private static String				IDENTIFIER_0		= IndexCOPListActivity.class
															.getSimpleName()
															+ "00";

	private CallbackHandlerOnIndexFutures	_callbackHandlerOnIndexFutures;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cop_index);

		_top_bar_title = (TextView) findViewById(R.id.top_bar_title);
		_toolBtnReturn = (Button) findViewById(R.id.more_returnbtn);
		_toolBtnReturn.setFocusable(true);
		_toolBtnReturn.setClickable(true);
		_toolBtnReturn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog.d(TAG,
						"close current activity and forwarding to the previous");

				Intent intent = new Intent(getApplicationContext(),
						IndexOptionsListActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				SwitchForwardActivity(IndexOptionsListActivity.class,
						intent);
			}

		});

		_listView = (ListView) findViewById(R.id.index_cop_list);
		_list = new Vector<IndexCopHolder>();
		int index = 0;
		for (String item : INDEX_FUTURES_ITEMS)
		{
			IndexCopHolder holder = new IndexCopHolder();
			holder.left = new TextView(this);
			holder.mid = new TextView(this);
			// holder.right = new Button(this);
			holder.id = index++;
			holder.itemCode = item;
			_list.add(holder);
		}
		_adapter = new IndexCopItemAdapter(LayoutInflater.from(this), _list);
		_listView.setAdapter(_adapter);

		// resetAdapterToAddAnotherClickableBtn(); // modiby zor(ouyangzhihui)
	}

	@Override
	protected void onResume()
	{
		// TODO Auto-generated method stub
		super.onResume();
		upateTitle();
		/*
		 * final Runnable myUpdateResults = new Runnable() { public void run() {
		 * connectLightStreamer(); } };
		 * 
		 * new Thread() { public void run() {
		 * _messageHandler.post(myUpdateResults); } }.start();
		 */

		/*
		 * if (!SystemInfo.isNetworkingConnected(this)) { new
		 * CustomizeDialog(getMyOwnContext(), getResources().getString(
		 * R.string.info), getResources().getString(
		 * R.string.networking_disconnect_tips)).show(); return; }
		 */

		/*
		 * if (_streamerTimeoutHandler != null) {
		 * _streamerTimeoutHandler.startCounter(0,0); }
		 */

		// onConnectionEstablished();
		new SubscriptionTask().execute();

	}

	private void upateTitle()
	{
		String titleContext = ((ITDLApplication) getApplicationContext())
				.getString(CommonDefn.TOP_BAR_TITLE);
		if (((ITDLApplication) getApplicationContext()).getDataMode() == CommonDefn.DataMode.Delay)
		{
			_top_bar_title.setText("COP("
					+ getResources().getString(
							R.string.delay_mode_title_tips) + ")");
		}
		else
		{
			_top_bar_title.setText(titleContext);
		}
		_top_bar_title.postInvalidate();

		((ITDLApplication) getApplicationContext()).putString(
				CommonDefn.TOP_BAR_TITLE, "");
	}

	private class CallbackHandlerOnIndexFutures implements
		LightStreamerHandlerInterface
	{
		public void onUpdate(final int itemPos, final String itemName,
				final UpdateInfo update)
		{
			final Runnable myUpdateResults = new Runnable()
			{
				public void run()
				{
					updateAdapter(itemPos, itemName, update);
				}
			};

			new Thread()
			{
				public void run()
				{
					if (_messageHandler != null)
						_messageHandler.post(myUpdateResults);
				}
			}.start();
		}

		public void updateAdapter(final int itemPos, final String itemName,
				final UpdateInfo update)
		{
			for (IndexCopHolder holder : _list)
			{
				if (holder.itemCode.equals(itemName))
				{

					// DT, 2011/01/14, format to 0 d.p., need to be the same as
					// iPhone app
					// holder.mid.setText(update.getNewValue(IndexFuturesInfo.COP));

					String tempCOP = update
							.getNewValue(IndexFuturesInfo.COP);
					// TDStockLog.d(TAG,
					// "isCop="+update.getNewValue(IndexFuturesInfo.ISCOP)+" , cop="+update.getNewValue(IndexFuturesInfo.COP)+" , last="+update.getNewValue(IndexFuturesInfo.LAST));
					// if(!"Y".equals(update.getNewValue(IndexFuturesInfo.ISCOP)))
					// {
					// tempCOP = update.getNewValue(IndexFuturesInfo.LAST);
					// }

					if (tempCOP == null || tempCOP.equals(""))
					{
						tempCOP = CommonDefn.DEFAULT_FIELD_VALUE2;
					}
					String formattedCOP = StringUtils.formatToDp(tempCOP,
							0);
					holder.mid.setText(formattedCOP);

					switch (itemPos - 1)
					{
						case 0:
						case 1:
							holder.left
									.setText(String.format(
											"恆生指數 %s月期貨",
											update.getNewValue(IndexFuturesInfo.MM)));
							break;
						default:
							holder.left
									.setText(String.format(
											"國企指數 %s月期貨",
											update.getNewValue(IndexFuturesInfo.MM)));
							break;
					}
				}

			}

			_listView.invalidateViews();

		}

	}

	@Override
	protected void onConnectionEstablished()
	{

		try
		{
			if (_callbackHandlerOnIndexFutures == null)
				_callbackHandlerOnIndexFutures = new CallbackHandlerOnIndexFutures();

			LS_SubscriptionItem interestItem = new LS_SubscriptionItem(
					IndexFuturesInfo.adapter_realtime);
			for (String item : INDEX_FUTURES_ITEMS)
				interestItem.AddSubscribeItem(item);
			interestItem.AddSubscribeSchema(IndexFuturesInfo.MM);
			interestItem.AddSubscribeSchema(IndexFuturesInfo.COP);
			// interestItem.AddSubscribeSchema(IndexFuturesInfo.LAST);
			// interestItem.AddSubscribeSchema(IndexFuturesInfo.ISCOP);

			// IDENTIFIER_0 = LSGetUniqueID();
			if (LightStreamerSubscribeItem(IDENTIFIER_0, interestItem, this))
			{

			}

		}

		catch (Exception e)
		{
			e.printStackTrace();
		}

	}

	private String[]	futuresCopNames	= { "恆%月C", "恆%月C", "國%月C", "國%月C" };

	public class AddItemClickHandler extends DefaultClickHandler
	{
		private String	_item;
		private String	_adapter;
		private String	_fieldName;
		private String	_fieldValue;
		private String	_fieldNet;
		private String	_fieldNetPercentage;

		public AddItemClickHandler(Context context, int pos)
		{
			super(context);
			setItemPos(pos);
		}

		public void setItemPos(int pos)
		{
			_item = INDEX_FUTURES_ITEMS[pos];
			_adapter = IndexFuturesInfo.ADAPTER + IndexFuturesInfo.COP;
			setFields(futuresCopNames[pos], "", "", "");
		}

		public void setFields(String name, String value, String net,
				String netpercentage)
		{
			_fieldName = name;
			_fieldValue = value;
			_fieldNet = net;
			_fieldNetPercentage = netpercentage;
		}

		@Override
		protected void onDefaultAction()
		{

			// 延迟模式
			if (((ITDLApplication) getApplicationContext()).getModeType() == CommonDefn.ModeType.DELARY)
			{
				DBHelper dbHelper = new DBHelper(IndexCOPListActivity.this);
				try
				{
					int customerId = 1;

					if (dbHelper.isSubscribeItemExist(customerId, _item,
							_adapter))
					{
						new CustomizeDialog(getMyOwnContext(), "",
								getResources().getString(
										R.string.monitor_exist_index))
								.show();
						/*
						 * new AlertDialog.Builder(
						 * IndexCOPListActivity.thisgetMyOwnContext())
						 * .setTitle( IndexCOPListActivity.this .getResources()
						 * .getString(R.string.info)) .setMessage(
						 * IndexCOPListActivity.this .getResources() .getString(
						 * R.string.monitor_exist_index)) .setIcon(
						 * IndexCOPListActivity.this .getResources()
						 * .getDrawable( R.drawable.help_menu_icon))
						 * .setPositiveButton( IndexCOPListActivity.this
						 * .getResources() .getString(R.string.ok), new
						 * DialogInterface.OnClickListener() { public void
						 * onClick( DialogInterface dialoginterface, int i) { }
						 * }).show();
						 */
					}
					else if (dbHelper.isFullWithItemInMonitor(customerId))
					{
						new CustomizeDialog(
								getMyOwnContext(),
								"",
								getResources()
										.getString(
												R.string.monitor_is_full_with_items))
								.show();
						/*
						 * new AlertDialog.Builder(
						 * ForeignExchangeActivity.thisgetMyOwnContext())
						 * .setTitle(getResources().getString(R.string.info))
						 * .setMessage(getResources().getString(R.string.
						 * monitor_is_full_with_items))
						 * .setIcon(getResources().getDrawable
						 * (R.drawable.help_menu_icon))
						 * .setPositiveButton(getResources
						 * ().getString(R.string.ok), new
						 * DialogInterface.OnClickListener(){ public void
						 * onClick(DialogInterface dialoginterface,int i)
						 * {}}).show();
						 */
					}
					else
					{
						long result = dbHelper.insertSubscribeItem(
								customerId, _item, _adapter,
								_fieldName, _fieldValue, _fieldNet,
								_fieldNetPercentage);
						if (result > 0)
						{
							/*
							 * new
							 * AlertDialog.Builder(CurrentStockInfoActivity.this
							 * )
							 * .setTitle(getResources().getString(R.string.info
							 * )) .setMessage(getResources().getString(R.string.
							 * monitor_add_to))
							 * .setIcon(getResources().getDrawable
							 * (R.drawable.help_menu_icon))
							 * .setPositiveButton(getResources
							 * ().getString(R.string.ok), new
							 * DialogInterface.OnClickListener(){ public void
							 * onClick(DialogInterface dialoginterface, int i){
							 * }}).show();
							 */
							// startAnim(genBitMapforAnim(_item));
							/* modify by zor(ouyangzhihui) */
							String temp = _item.length() >= 2 ? _item
									.substring(0, 2) : _item;
							startAnimat(temp);
							TDStockLog.d(TAG, "insert result:" + result);
						}
					}

				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
					TDStockLog.d(
							TAG,
							"insert result:" + e.getMessage() == null ? "unknown exception!"
									: e.getMessage());
				}
				finally
				{
					dbHelper.cleanup();
				}
			}
			// 非延迟模式
			else
			{
				new SaveBookMarkAsyncTask(_item,
						CommonDefn.BookMarkType.cop.getBookMarkType(),
						IndexCOPListActivity.this,
						MonitorUtil.getInstance(),
						_item.length() >= 2 ? _item.substring(0, 2)
								: _item).execute();

			}

		}

	}

	protected Context getMyOwnContext()
	{
		// return _context;
		return getParent();
	}

	private class SubscriptionTask extends AsyncTask<String, Void, Void>
	{

		@Override
		protected Void doInBackground(String... params)
		{
			onConnectionEstablished();
			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			super.onPostExecute(result);
		}

	}

	// modify by zor(ouyangzhihui)
	public class IndexCopItemAdapter extends BaseAdapter
	{
		// private static String TAG =
		// IndexCopItemAdapter.class.getSimpleName();
		private LayoutInflater		minflater;
		private List<IndexCopHolder>	list;

		public IndexCopItemAdapter(LayoutInflater inflater,
				List<IndexCopHolder> list)
		{
			super();
			this.minflater = inflater;
			this.list = list;
		}

		@Override
		public int getCount()
		{
			return this.list.size();
		}

		@Override
		public Object getItem(int position)
		{
			return position < this.list.size() ? this.list.get(position)
					: null;
		}

		@Override
		public long getItemId(int position)
		{
			return position < this.list.size() ? this.list.get(position).id
					: -1l;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			IndexCopHolder commHolder = null;
			if (convertView == null)
			{
				convertView = minflater.inflate(R.layout.index_cop_item,
						null);
				commHolder = new IndexCopHolder();
				commHolder.left = (TextView) convertView
						.findViewById(R.id.cop_item_left);
				commHolder.mid = (TextView) convertView
						.findViewById(R.id.cop_item_mid);
				commHolder.right = (ImageView) convertView
						.findViewById(R.id.cop_item_right);

				commHolder.mid.setGravity(Gravity.RIGHT);
				// synchronize with iphone
				commHolder.left.setTextColor(Color.BLUE);
				commHolder.mid.setTextColor(Color.BLACK);
				convertView.setDrawingCacheBackgroundColor(Color.WHITE);

				// synchronize with iphone

				convertView.setTag(commHolder);
			}
			else
			{
				commHolder = (IndexCopHolder) convertView.getTag();
			}
			// modify by zor(ouyangzhihui)
			commHolder.right.setOnClickListener(new AddItemClickHandler(
					IndexCOPListActivity.this, position));

			if (this.list.get(position) != null
					&& this.list.get(position).left != null
					&& this.list.get(position).left.getText() != null)
				commHolder.left.setText(this.list.get(position).left
						.getText());
			if (this.list.get(position) != null
					&& this.list.get(position).mid != null
					&& this.list.get(position).mid.getText() != null)
				commHolder.mid.setText(this.list.get(position).mid
						.getText());

			return convertView;
		}

	}

	@Override
	public ActivityGroupController GetActivityGroupController()
	{
		return IndexGroup.GetActivityGroupHostControl();
	}

	@Override
	protected void onPause()
	{
		super.onPause();
	}

	@Override
	public void onUpdate(String iIdentifier, int iSchemaIndex,
			String iSchemaValue, UpdateInfo iUpdateInfo)
	{
		super.onUpdate(iIdentifier, iSchemaIndex, iSchemaValue, iUpdateInfo);
		if (IDENTIFIER_0.equals(iIdentifier))
		{
			_callbackHandlerOnIndexFutures.onUpdate(iSchemaIndex,
					iSchemaValue, iUpdateInfo);
		}
	}
}
